// 引入axios
import axios from "axios";
import { AxiosInstance } from "axios";
import { ElMessage } from "element-plus";
// 引入token所在的仓库
import useUserStore from "@/store/modules/user";
// 不能在这里设置获取仓库实例，因为这个时候仓库还没有初始化完成
// const UserStore = useUserStore();
// 创建实例
const request: AxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 30000, // 30秒,
});

// 配置请求和响应拦截器
request.interceptors.request.use((config) => {
    const UserStore = useUserStore();
    // 在请求拦截器中为请求头添加上token字段
    if (UserStore.token) {
        config.headers.token = UserStore.token;
    }
    return config;
});

request.interceptors.response.use(
    (response) => {
        return response.data;
    },
    (error) => {
        // 请求中断作特殊处理
        if (error.code === "ERR_CANCELED") {
            return {
                code: 0,
                data: "cancel",
                message: "请求被取消",
            } as ResponseData<string>;
        }
        let message: string = "";
        const status: number = error.response.status;
        switch (status) {
            case 401:
                message = "token过期";
                break;
            case 403:
                message = "无权访问";
                break;
            case 404:
                message = "请求地址错误";
                break;
            case 500:
                message = "服务器出现问题";
                break;
            default:
                message = "无网络";
        }

        ElMessage({
            type: "error",
            message: message,
        });
        return Promise.reject(error);
    },
);

export default request;
